/**
 * Bendra klasė darbui su hsql duomenų baze.
 * 
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


public class DB {
    Connection conn;
	
    public DB(String dbFileName) throws Exception{
    	Class.forName("org.hsqldb.jdbc.JDBCDriver");
    	conn = DriverManager.getConnection("jdbc:hsqldb:" + dbFileName, "SA", ""); 
	}
    
    public void shutdown() throws SQLException {
        Statement st = conn.createStatement();
        st.execute("SHUTDOWN");
        conn.close();
    }
    
    public synchronized ArrayList<String> query(String expression) throws SQLException {
    	
        Statement st = null;
        ResultSet rs = null;

        st = conn.createStatement();
        rs = st.executeQuery(expression);

        ArrayList<String> result = dump(rs);
        st.close();
        
        return result;
    }
    
    public synchronized void update(String expression) throws SQLException {

        Statement st = null;

        st = conn.createStatement();

        int i = st.executeUpdate(expression);

        if (i == -1) {
            System.out.println("db error : " + expression);
        }

        st.close();
    }
    
    public static ArrayList<String> dump(ResultSet rs) throws SQLException {
    	ArrayList<String> result = new ArrayList<String>();

        ResultSetMetaData meta   = rs.getMetaData();
        int colmax = meta.getColumnCount();
        int i;
        Object o = null;

        for (; rs.next(); ) {
            for (i = 0; i < colmax; ++i) {
                o = rs.getObject(i + 1);

                if(o != null){
                    result.add(o.toString());
                }
            }

        }
        return result;
    } 
}
